import {Message} from "./message";

export class WebSocketClient {
    url:string;
    ws:WebSocket;
    constructor(url:string) {
        this.url = url;
        this.ws = new WebSocket(url);
    }
    connect() {
        this.ws.onopen = () => {
            console.log('WebSocket连接已打开');

        };

    }
    send(message:Message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        } else {
            console.error('WebSocket连接未建立或已关闭，无法发送消息');
        }
    }

    close() {
        if (this.ws) {
            this.ws.close();
        }
    }
}

// 使用示例
// const wsClient = new WebSocketClient('ws://localhost:3000');
// wsClient.connect();
// wsClient.send('Hello, server!');
